package com.zxy.intercept;

import cn.echo.threadlocal.LocalUserUtils;
import com.zxy.model.BaseModel;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import java.sql.PreparedStatement;
import java.util.Properties;
//参数拦截器
@Component
@Intercepts(@Signature(type = ParameterHandler.class,method = "setParameters",args = {PreparedStatement.class}))
//通过注解@Intercepts 指定参数拦截器类型的签名，并且还要指定设置参数PreparedStatement类型的方法
//当在执行的时候进行拦截
//拦截的执行顺序是Executor->StatementHandler->ParameterHandler->ResultHandler
public class ParameterPlugin implements Interceptor {
//    核心 intercept
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
//        这个getTarget是拦截目标类
       ParameterHandler parameterHandler  = (ParameterHandler)invocation.getTarget();

        Object parameterObject = parameterHandler.getParameterObject();
//        判断类型 是否有BaseModel
        if(parameterObject instanceof BaseModel){
            BaseModel model = (BaseModel) parameterObject;
//            看调用对象是否是BaseModel，如果是，那么model就直接赋值，业务代码不需要再写了
            model.setLastUpdateBy(LocalUserUtils.get().getNickName());
        }

//       调用目标方法
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Interceptor.super.plugin(target);
    }

    @Override
    public void setProperties(Properties properties) {

    }
//    参数拦截





}
